package cn.ickck.law_paper_final.controller;

import cn.ickck.law_paper_final.model.entity.CreditCard;
import cn.ickck.law_paper_final.model.entity.CreditCardBatch;
import cn.ickck.law_paper_final.model.response.CreditCardBatchResponse;
import cn.ickck.law_paper_final.service.CreditCardBatchService;
import cn.ickck.law_paper_final.service.CreditCardService;
import cn.ickck.law_paper_final.utils.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @Author: ck
 * @Description:
 * @Date: Create in 12:19 2020/10/23
 */
@RestController
@RequestMapping("/api/v2/pub/credit_card_batch")
public class CreditCardBatchController {
    @Autowired
    private CreditCardBatchService creditCardBatchService;
    @Autowired
    private CreditCardService creditCardService;

    @RequestMapping("findBatchByPage")
    public JsonData findAllBatch(@Param("page") Integer page) {
        int count = creditCardBatchService.Count();
        CreditCardBatchResponse creditCardBatchResponse = new CreditCardBatchResponse();
        creditCardBatchResponse.setCount(count);
        int start = count - page * 20 > 0 ? count - page * 20 : 0;
        int end = count - (page - 1) * 20 > 0 ? count - (page - 1) * 20 : count;
        List<CreditCardBatch> creditCardBatches = creditCardBatchService.findByPage(start, end);
        creditCardBatchResponse.setCreditCardBatches(creditCardBatches);
        return JsonData.buildSuccess(creditCardBatchResponse);
    }

    @RequestMapping("findByName")
    public JsonData findBatchByName(@Param("page") Integer page, @Param("name") String name) {
        CreditCardBatchResponse creditCardBatchResponse = new CreditCardBatchResponse();
        List<CreditCardBatch> creditCardBatches = creditCardBatchService.findBatchByName(name);
        creditCardBatchResponse.setCount(creditCardBatches.size());
        List<CreditCardBatch> creditCardBatches1 = new ArrayList<>();
        int start = creditCardBatches.size() - page * 20 > 0 ? creditCardBatches.size() - page * 20 : 0;
        int end = creditCardBatches.size() - (page - 1) * 20 > 0 ? creditCardBatches.size() - (page - 1) * 20 : creditCardBatches.size();
        for (int i = start; i < end; i++) {
            creditCardBatches1.add(creditCardBatches.get(i));
        }
        creditCardBatchResponse.setCreditCardBatches(creditCardBatches1);
        return JsonData.buildSuccess(creditCardBatchResponse);
    }

    //多步操作，建议加事务控制
    @Transactional
    @RequestMapping("deleteById")
    public JsonData deleteById(Integer id) {

        String key = creditCardBatchService.findKeyById(id).getKey();
        System.out.println("key是多少:" + key);
        creditCardBatchService.deleteById(id);
        creditCardService.deleteByKey(key);

        return JsonData.buildSuccess("删除成功");
    }



    @RequestMapping("update")
    public JsonData update(@RequestBody CreditCardBatch creditCardBatch) {
        creditCardBatchService.update(creditCardBatch);
        return JsonData.buildSuccess();
    }

    //导出信用卡的所有数据
    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse httpServletResponse, @RequestBody CreditCardBatch creditCardBatch) throws Exception {
        List<CreditCard> creditCards = creditCardService.findByNameOrKey(creditCardBatch.getKey());
        ExcelUtils.exportExcel(creditCards, CreditCard.class, creditCardBatch.getName() + ".xlsx", httpServletResponse);
    }

    //导出民事起诉状的大Word

    @RequestMapping("exportWord")
    public void exportWord(HttpServletResponse response, @RequestBody CreditCardBatch creditCardBatch) throws Exception {
        List<CreditCard> creditCards = creditCardService.findByNameOrKey(creditCardBatch.getKey());

        Map data = new HashMap<>();
        System.out.println("调用方法");

        data.put("creditCards", creditCards);
        response.setHeader("content-Type", "application/msword");

        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;


        try {
            template = cfg.getTemplate("民事起诉状-信用卡借款.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "民事起诉状-信用卡借款");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导出民事起诉状的zip
    @RequestMapping("exportZip")
    public void exportZip(HttpServletResponse httpServletResponse, @RequestBody CreditCardBatch creditCardBatch) {

        List<CreditCard> creditCards = creditCardService.findByNameOrKey(creditCardBatch.getKey());

        List<File> files = new ArrayList<>();
        for (CreditCard creditCard : creditCards) {

            Map data = new HashMap<>();
            List<CreditCard> creditCards1 = new ArrayList<>();
            creditCards1.add(creditCard);
            data.put("creditCards", creditCards1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = creditCard.getParty() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "民事起诉状-信用卡借款.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }

    }


    //导出强制执行申请书的大word
    @RequestMapping("exportWord_1")
    public void exportWord_1(HttpServletResponse response, @RequestBody CreditCardBatch creditCardBatch) throws Exception {

        List<CreditCard> creditCards = creditCardService.findByNameOrKey(creditCardBatch.getKey());

        Map data = new HashMap<>();
        System.out.println("调用方法");

        data.put("creditCards", creditCards);
        response.setHeader("content-Type", "application/msword");

        // 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 指定FreeMarker模板文件的位置
        cfg.setClassForTemplateLoading(getClass(), "/templates");
        Template template = null;


        try {
            template = cfg.getTemplate("强制执行申请书-信用卡.ftl", "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
        }


        OutputStream outputStream = response.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);


        try {
            DownLoadFileUtil.setResponseHeader(response, "强制执行申请书-信用卡.doc");
            template.process(data, outputStreamWriter);
//            System.out.println(outputStreamWriter);
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //导出强制执行申请书的zip
    @RequestMapping("exportZip_1")
    public void exportZip_1(HttpServletResponse httpServletResponse, @RequestBody CreditCardBatch creditCardBatch) {

        List<CreditCard> creditCards = creditCardService.findByNameOrKey(creditCardBatch.getKey());

        List<File> files = new ArrayList<>();
        for (CreditCard creditCard : creditCards) {

            Map data = new HashMap<>();
            List<CreditCard> creditCards1 = new ArrayList<>();
            creditCards1.add(creditCard);
            data.put("creditCards", creditCards1);

            String filePath = FileUtils.getWordPath();
            //文件唯一名称
            String fileOnlyName = creditCard.getParty() + UUID.randomUUID().toString() + ".doc";
            /** 生成word  数据包装，模板名，文件生成路径，生成的文件名*/

            WordUtil.createWord(data, "强制执行申请书-信用卡.ftl", filePath, fileOnlyName);
            File f = new File(filePath + File.separator + fileOnlyName);
            files.add(f);
        }

        //调用压缩
        String time = System.currentTimeMillis() + "";
        String zipFilePath = FileUtils.getWordPath() + File.separator + time + ".zip";
        try {
            ZipUtil.create(zipFilePath, files);
            //下载文件
            File f = new File(zipFilePath);
            if (f.exists()) {
                ZipUtil.downloadZip(f, httpServletResponse);
//                DownLoadFileUtil.setResponseHeader(response,zipFilePath);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (File file : files) {
            file.delete();
        }

    }








}
